<template>
    <!-- 商家页 -->

    <van-nav-bar
      :title="shopperData.shopper"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
  <div class="page">
<header class="header">
    <div class="img-wrapper">
        <van-image 
        width="100%"
        height="25vh"
        position="top"
        src="https://img0.baidu.com/it/u=4049425788,3023392160&fm=253&fmt=auto&app=120&f=JPEG?w=889&h=500">
            <template v-slot:loading>
              <van-loading type="spinner" size="20" />
            </template>
          </van-image>
    </div>

    <!-- 商家介绍区域 -->
    <div class="shopper-info">
      <div class="shop-header">
        <van-image
        round
        width="1.6rem"
        height="1.6rem"
        fit="cover"
        position="center"
        src="https://img2.baidu.com/it/u=350449573,3614236444&fm=253&fmt=auto?w=596&h=954"
      class="shop-logo"/>
        <div class="shop-basic-info">
          <h2 class="shop-name">{{ shopperData.shopper }}</h2>
          <div class="shop-metrics">
            <div class="metric-item">
              <span class="metric-label">评分</span>
              <span class="metric-value score">{{ randomShopData.rating }}</span>
            </div>
            <div class="metric-item">
              <span class="metric-label">月售</span>
              <span class="metric-value">{{ randomShopData.monthlySales }}+</span>
            </div>
            <div class="metric-item">
              <span class="metric-label">配送</span>
              <span class="metric-value">约{{ randomShopData.deliveryTime }}分钟</span>
            </div>
          </div>
          <div class="shop-location">
            <span class="location-text">良子鼎力推荐</span>
            <span class="rank-text">人气第4名</span>
          </div>
        </div>
      </div>
      
      <!-- 优惠券区域 -->
      <div class="coupon-section">
        <div class="coupon-item active">
          <span class="coupon-type">神券</span>
          <span class="coupon-value">¥13满32可用</span>
          <span class="coupon-status" v-if="!shopperStore.hasCoupon" @click="getCoupon" style="color: red;">领取</span>
          <span class="coupon-status" v-else>已领</span>
        </div>
      </div>
      
      <!-- 促销标签区域 -->
      <div class="promotion-tags">
        <van-tag plain type="primary" class="promotion-tag">9.9折起</van-tag>
        <van-tag plain type="primary" class="promotion-tag">新客减1</van-tag>
      </div>
      
      <!-- 商家公告 -->
      <div class="shop-notice">
        <span class="notice-text">外卖全天送楼下</span>
      </div>
    </div>
</header>

<main class="main">
   <!-- TODO: 商家页增加切换栏 (点餐 评价 商家介绍栏)  -->
    <!-- !点餐栏是种类区分 在这里就不做区分了 主要是练习渲染数据为主 -->
<div class="tab">
  <van-tabs v-model:active="tabActiveName" swipeable>
    <van-tab title="点餐" name="order">
<!-- 侧边导航 -->
 <div class="sidebar-wrapper">
<van-sidebar v-model="sideBarActiveIndex" class="sidebar" @change="onSidebarChange">
  <van-sidebar-item title="热销套餐" />
  <van-sidebar-item title="新品尝鲜" />
  <van-sidebar-item title="会员优惠" />
</van-sidebar>
</div>
<div class="content-wrapper">
  <div class="product-list">
    <div class="category-header">
      <h3 class="category-title">{{ getCurrentCategoryName }}</h3>
    </div>
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多商品了"
      error-text="加载失败，请重试"
      :error="error"
      @load="onLoad"

    >
      <NavListItem v-for="item in productData" :key="item.id" :data="item" />
    </van-list>
  </div>
</div>
    </van-tab>
    <van-tab title="评价" name="comment">
      <!--  TODO: 评论列表  也是实现一个CommentList组件得了来渲染 以及 CommentItem-->
      <van-list
      v-model="commentLoading"
      :finished="commentFinished"
      finished-text="拿再多数据 我的接口会被玩坏的"
      error-text="加载失败,请重试"
      @load="onCommentLoad"
      :error="commentError"
      >

<CommentIListItem v-for="item in commentList" :key="item.id" :comment="item.comment" />
      </van-list>
      
    </van-tab>
    <van-tab title="商家" name="shopper"></van-tab>
<!-- TODO:商家介绍 这里就简单的写点静态数据即可  模仿美团-->
  </van-tabs>
</div>


</main>


  </div>
</template>

<script setup>
import CommentIListItem from '../../components/CommentIListItem.vue'
import { useShopperStore } from '@store/shopper'
import { useRouter } from 'vue-router'
import {reactive, ref ,onUnmounted, onMounted, computed} from 'vue'
import NavListItem from '@/components/NavListItem.vue'
const shopperStore = useShopperStore()
const router = useRouter()
import { showSuccessToast } from 'vant'
const tabActiveName = ref('order')
const sideBarActiveIndex = ref(0)
const commentLoading = ref(false)
const commentFinished=ref(false)
// 商品列表数据
const productData = reactive([])
const loading = ref(false)
const finished = ref(false)
const error = ref(false)
const commentError=ref(false)
const currentType = ref('hot') // 当前选中的类型：hot, new, member
const commentList = reactive([
  {
    id: 1,
    comment: '这个商家的商品都很美味，推荐给大家！'
  },
])
 const commentListLength = computed(() => commentList.length)
defineOptions({
  name: 'ShopperIndex',
})
const onCommentLoad = async () => { 
      // 检查是否已经达到10条评论
      if (commentList.length >= 10) {
      commentFinished.value = true
      return
    }
   commentLoading.value = true
   try {
    // 直接请求数据，不使用setTimeout延迟
    const comment = await shopperStore.getOneComment()
    commentList.push({
      id: commentListLength.value + 1,
      comment
    })

    
   } catch (error) {
    commentError.value = true
   } finally {
     commentLoading.value = false
   }
   }

// 生成随机商家数据
const generateRandomShopData = () => {
  return {
    rating: (Math.random() * 2 + 3).toFixed(1), // 3.0-5.0分
    monthlySales: Math.floor(Math.random() * 2000) + 100, // 100-2100单
    deliveryTime: Math.floor(Math.random() * 30) + 20, // 20-50分钟
    rank: Math.floor(Math.random() * 20) + 1 // 1-20名
  }
}

const randomShopData = reactive(generateRandomShopData())

// 商家数据
const shopperData = reactive({
    shopper: shopperStore.shopper || '默认商家'
})
const onClickLeft = () => {
  router.back()
}
const getCoupon = () => {
    shopperStore.hasCoupon = true
    showSuccessToast('领取成功')
}

// 模拟加载商品数据
const onLoad = () => {
  loading.value = true
  
  // 模拟异步加载
  setTimeout(() => {
    try {
      // 获取 当前商家的商品数据，不筛选type
      const allData = shopperStore.getCurrentShopperData()
      
      if (allData && allData.length > 0) {
        Object.assign(productData, allData)
        finished.value = true
        error.value = false
        console.log(`加载了 ${allData.length} 个商品，当前类型: ${currentType.value}`)
      } else {
        console.warn('没有商品数据')
        error.value = true
      }
    } catch (err) {
      console.error('加载商品数据失败:', err)
      error.value = true
    } finally {
      loading.value = false
    }
  }, 600)
}

// 侧边栏切换事件
const onSidebarChange = (index) => {
  console.log('侧边栏切换:', index)
  // 设置当前类型
  const types = ['hot', 'new', 'member']
  currentType.value = types[index] || 'hot'
  
  // 重新加载数据（虽然数据一样，但可以添加不同的加载效果）
Object.assign(productData, {})
  finished.value = false
  error.value = false
  
  // 立即加载数据
  onLoad()
}

// 获取当前分类名称的计算属性
const getCurrentCategoryName = computed(() => {
  const names = {
    'hot': '热销套餐',
    'new': '新品尝鲜', 
    'member': '会员优惠'
  }
  return names[currentType.value] || '热销套餐'
})

// 组件挂载时加载数据
onMounted(() => {
  onLoad()
})

onUnmounted(() => {
  shopperStore.reset()
});
</script>

<style scoped lang="scss">
// 基础变量
$primary-color: #ff6b35;
$secondary-color: #ffc400;
$bg-color: #fafafa;
$sidebar-bg: #f8f8f8;
$text-primary: #333;
$text-secondary: #666;
$text-muted: #999;
$border-color: #eee;

// 头部样式
.header {
  .img-wrapper {
    overflow: hidden;
    border-radius: 8px;
  }
}

// 商家介绍区域
.shopper-info {
  padding: 16px;
  background: white;
  
  .shop-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    .shop-logo {
margin-right: 12px;
    }

    .shop-basic-info {
      flex: 1;

      .shop-name {
        font-size: 18px;
        font-weight: 600;
        margin: 0 0 8px 0;
        color: $text-primary;
      }

      .shop-metrics {
        display: flex;
        gap: 16px;
        margin-bottom: 6px;

        .metric-item {
          display: flex;
          flex-direction: column;
          align-items: center;

          .metric-label {
            font-size: 12px;
            color: $text-muted;
            margin-bottom: 2px;
          }

          .metric-value {
            font-size: 14px;
            color: $text-primary;

            &.score {
              color: $primary-color;
              font-weight: 500;
            }
          }
        }
      }

      .shop-location {
        font-size: 12px;
        color: $text-secondary;

        .rank-text {
          color: $primary-color;
          margin-left: 8px;
        }
      }
    }
  }

  // 优惠券区域
  .coupon-section {
    margin-bottom: 12px;

    .coupon-item {
      display: flex;
      align-items: center;
      padding: 10px 12px;
      background: #fff7e6;
      border-radius: 8px;
      border: 1px solid #ffd166;

      &.active {
        background: linear-gradient(135deg, #fff7e6, #ffedcc);
      }

      .coupon-type {
        background: $primary-color;
        color: white;
        font-size: 12px;
        padding: 2px 6px;
        border-radius: 4px;
        margin-right: 8px;
      }

      .coupon-value {
        // 使用flex=1将领取(span)撑到最后
        flex: 1;
        font-size: 14px;
        color: $primary-color;
        font-weight: 500;
      }

      .coupon-status {
        font-size: 12px;
        color: $text-muted;
      }
    }
  }

  // 促销标签
  .promotion-tags {
    display: flex;
    gap: 8px;
    margin-bottom: 12px;

    .promotion-tag {
      font-size: 12px;
    }
  }

  // 商家公告
  .shop-notice {
    display: flex;
    align-items: center;
    font-size: 12px;
    color: $text-secondary;

    .notice-text {
      margin: 0 auto;
      margin-bottom: 0;
    }
  }
}

// 点餐区域布局
.main {
  .tab {
    background: white;
    top: 0;

    :deep(.van-tabs__line) {
      background-color: $secondary-color;
    }
  }

  .sidebar {
    :deep(.van-sidebar-item--select::before) {
      background-color: $secondary-color;
    }
  }
}

// 侧边栏布局
.sidebar-wrapper {
  width: 80px;
  float: left;
  background: $sidebar-bg;
  min-height: 400px;

  .sidebar {
    width: 80px;

    :deep(.van-sidebar-item) {
      padding: 12px 8px;
      font-size: 12px;
      text-align: center;
    }

    :deep(.van-sidebar-item--select) {
      background: white;
      color: $primary-color;
      font-weight: 500;
    }
  }
}

// 内容区域
.content-wrapper {
  margin-left: 80px;
  padding: 0;
  background: $bg-color;
  min-height: 400px;

  .product-list {
    padding: 16px;
    background-color: $bg-color;
    min-height: 400px;

    .category-header {
      margin-bottom: 16px;
      padding: 12px 0;
      border-bottom: 1px solid $border-color;

      .category-title {
        font-size: 18px;
        font-weight: 600;
        color: $text-primary;
        margin: 0;
      }
    }

    :deep(.van-list) {
      background: transparent;
    }

    :deep(.van-list__finished-text),
    :deep(.van-list__error-text) {
      color: $text-muted;
      font-size: 14px;
      padding: 20px 0;
    }
  }
}




</style>